package com.cargo.base.utils;

import com.cargo.base.servlet.bean.SendRequestBean;
import com.google.gson.Gson;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 
 * HttpSendUtils:远程接口调用工具类
 * @Project Name:templateproject 
 * @File Name:HttpSendUtils.java 
 * @Package Name:com.cargo.utils
 * @Creator:wizard
 * @Date:2016年10月31日下午12:02:48
 */
public class HttpSendUtils {
	
	private static final Logger Log = Logger.getLogger(HttpSendUtils.class);
	
	/**
	 * 
	 * connectURL:(通过json远程交互severlet).
	 * @param dest_url
	 * @param commString
	 * @return 
	 * @return :String 
	 * @Creator:wizard
	 * @Date:2016年10月31日 下午12:03:37
	 */
	public static String connectURL(String dest_url, String commString) {

		String rec_string = "";
		URL url = null;
		HttpURLConnection urlconn = null;
		OutputStream out = null;
		BufferedReader rd = null;
		try {
			url = new URL(dest_url);
			urlconn = (HttpURLConnection) url.openConnection();
			urlconn.setReadTimeout(1000 * 40);
			// urlconn.setRequestProperty("content-type", "text/html;charset=UTF-8");
			urlconn.setRequestMethod("POST");

			urlconn.setDoInput(true);
			urlconn.setDoOutput(true);
			out = urlconn.getOutputStream();
			StringBuffer temp = new StringBuffer("body=");
			temp.append(commString);
			out.write(temp.toString().getBytes("UTF-8"));
			out.flush();
			out.close();
			rd = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
			StringBuffer sb = new StringBuffer();
			int ch;
			while ((ch = rd.read()) > -1)
				sb.append((char) ch);
			rec_string = sb.toString();
		} catch (Exception e) {
			Log.error(e, e);
			return "";
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (urlconn != null) {
					urlconn.disconnect();
				}
				if (rd != null) {
					rd.close();
				}
			} catch (Exception e) {
				Log.error(e, e);
			}
		}

		return rec_string;
	}
	
	
	public static String send(SendRequestBean srb, Object paramsObj)throws Exception{
		
		String result = "";
		
		Gson gson = new Gson();
		String content = gson.toJson(paramsObj);
		
		srb.setContent(content);
		
		String json = gson.toJson(srb);
//		String url = "http://192.168.1.171:8080/edi/openapi/reviceservlet";
		
		String url = "http://localhost:8080/esea/client/commonservlet";
		
		result = connectURL(url, json);
		return result;
	}

}
